﻿namespace LivePatterns
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Reflection;
    using System.Reflection.Emit;

	public static partial class Build
	{
		/// <summary>
		/// Implements <see cref="System.ComponentModel.INofityPropertyChanged"/> on any kind of object and reports every property change.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="obj"></param>
		/// <returns>Returns a proxy instance that implements <see cref="System.ComponentModel.INofityPropertyChanged"/> and reports every property change.</returns>
		/// <remarks>Any kind of object can be converted, properties in models and view models can be declared using the short form automatic property implementation syntax.</remarks>
		/// <example>
		/// IArticle article = Build.NotifyPropertyChanged&lt;IArticle&gt;(DataContext.Repository&lt;IArticle&gt;().Get("first"));
		/// viewModelPresenter.DataContext = article;
		/// article.Title = "Changed Title";
		/// </example>
		public static T NotifyPropertyChanged<T>(T obj) where T : class
		{
			if (typeof(T).GetInterfaces().Contains(typeof(INotifyPropertyChanged)))
				return obj;

			if (!typeof(T).IsInterface)
				throw new ArgumentException("Only interface types are supported.");

            // resolve type from cache, if already built
            if (_notifyPropertyChangedTypeCache.ContainsKey(typeof(T)))
                return Activator.CreateInstance(_notifyPropertyChangedTypeCache[typeof(T)], obj) as T;

			TypeBuilder typeBuilder = moduleBuilder.DefineType(String.Format("{0}_NotificationProxy_{1}", typeof(T).Name, Guid.NewGuid().ToString().Replace("-", "")), TypeAttributes.Class | TypeAttributes.Public);
			typeBuilder.AddInterfaceImplementation(typeof(T));
			typeBuilder.AddInterfaceImplementation(typeof(INotifyPropertyChanged));

			// create a field for storing the real object instance
			FieldBuilder inner = typeBuilder.DefineField("innerObject", typeof(T), FieldAttributes.Family);

			// create a construtor, in which we can pass the real object instance
			ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(T) });
			ILGenerator cilg = constructorBuilder.GetILGenerator();
			cilg.ConstructObject();
			cilg.Emit(OpCodes.Ldarg_0);
			cilg.Emit(OpCodes.Ldarg_1);
			cilg.Emit(OpCodes.Stfld, inner);

			// implement INPC interface
			EventInfo pcei = typeof(T).GetEvent("PropertyChanged");
			FieldBuilder fieldBuilder = null;

			if (pcei == null || pcei.EventHandlerType != typeof(PropertyChangedEventHandler))
			{
				EventInfo inpc = typeof(INotifyPropertyChanged).GetEvent("PropertyChanged");

				// define event
				EventBuilder eb = typeBuilder.DefineEvent("PropertyChanged", EventAttributes.None, inpc.EventHandlerType);
				MethodBuilder methodBuilder;
				ILGenerator ilGenerator;

				// define backing field
				fieldBuilder = typeBuilder.DefineField(String.Format("PropertyChanged"), inpc.EventHandlerType, FieldAttributes.Private);

				//
				// implement add method
				//
				MethodInfo addMethod = inpc.GetAddMethod();
				methodBuilder = typeBuilder.DefineMethod(
					addMethod.Name, _methodAttributes, addMethod.ReturnType, addMethod.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.Emit(OpCodes.Ldarg_0);
				ilGenerator.Emit(OpCodes.Ldarg_0);
				ilGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
				ilGenerator.Emit(OpCodes.Ldarg_1);
				ilGenerator.Emit(OpCodes.Call, typeof(Delegate).GetMethod("Combine", new Type[] { typeof(Delegate), typeof(Delegate) }));
				ilGenerator.Emit(OpCodes.Castclass, typeof(PropertyChangedEventHandler));
				ilGenerator.Emit(OpCodes.Stfld, fieldBuilder);
				ilGenerator.Return();
				eb.SetAddOnMethod(methodBuilder);

				//
				// implement remove method
				//
				MethodInfo removeMethod = inpc.GetRemoveMethod();
				methodBuilder = typeBuilder.DefineMethod(
					removeMethod.Name, _methodAttributes, removeMethod.ReturnType, removeMethod.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.Emit(OpCodes.Ldarg_0);
				ilGenerator.Emit(OpCodes.Ldarg_0);
				ilGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
				ilGenerator.Emit(OpCodes.Ldarg_1);
				ilGenerator.Emit(OpCodes.Call, typeof(Delegate).GetMethod("Remove", new Type[] { typeof(Delegate), typeof(Delegate) }));
				ilGenerator.Emit(OpCodes.Castclass, typeof(PropertyChangedEventHandler));
				ilGenerator.Emit(OpCodes.Stfld, fieldBuilder);
				ilGenerator.Return();
				eb.SetRemoveOnMethod(methodBuilder);
			}

			// implement fields
			foreach (FieldInfo fi in typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance).Where(m => !m.IsSpecialName))
			{
				FieldBuilder fb = typeBuilder.DefineField(fi.Name, fi.FieldType, FieldAttributes.Public);

				// build constructor
				cilg.Emit(OpCodes.Ldarg_0);
				cilg.Emit(OpCodes.Ldarg_1);
				cilg.Emit(OpCodes.Ldfld, fi);
				cilg.Emit(OpCodes.Stfld, fb);
			}

			cilg.Emit(OpCodes.Ret);

			// implement properties
			foreach (PropertyInfo pi in typeof(T).GetAllVisibleProperties())
			{
				// define property
				PropertyBuilder pb = typeBuilder.DefineProperty(pi.Name, PropertyAttributes.None, typeof(int), Type.EmptyTypes);
				MethodBuilder methodBuilder;
				ILGenerator ilGenerator;

				MethodInfo getMethod = pi.GetGetMethod();

				//
				// implement get method
				//
				if (pi.CanRead)
				{
					methodBuilder = typeBuilder.DefineMethod(
						getMethod.Name, _methodAttributes, pi.PropertyType, getMethod.GetParameters().Select(p => p.ParameterType).ToArray()
					);

					ilGenerator = methodBuilder.GetILGenerator();
					ilGenerator.Emit(OpCodes.Ldarg_0);
					ilGenerator.Emit(OpCodes.Ldfld, inner);
					ilGenerator.Emit(OpCodes.Call, getMethod);
					ilGenerator.Return();
					pb.SetGetMethod(methodBuilder);
				}

				//
				// implement set method
				//
				if (pi.CanWrite)
				{
					MethodInfo setMethod = pi.GetSetMethod();
					methodBuilder = typeBuilder.DefineMethod(
						setMethod.Name, _methodAttributes, setMethod.ReturnType, setMethod.GetParameters().Select(p => p.ParameterType).ToArray()
					);
					methodBuilder.DefineParameter(1, ParameterAttributes.None, "value");

					ilGenerator = methodBuilder.GetILGenerator();
					Label el = ilGenerator.DefineLabel();
					if (pi.CanRead)
					{
						ilGenerator.Emit(OpCodes.Ldarg_1);
						ilGenerator.Emit(OpCodes.Ldarg_0);
						ilGenerator.Emit(OpCodes.Ldfld, inner);
						ilGenerator.Emit(OpCodes.Call, getMethod);
						ilGenerator.Emit(OpCodes.Ceq);
						ilGenerator.Emit(OpCodes.Brtrue_S, el);
					}

					ilGenerator.Emit(OpCodes.Ldarg_0);
					ilGenerator.Emit(OpCodes.Ldfld, inner);
					ilGenerator.Emit(OpCodes.Ldarg_1);
					ilGenerator.Emit(OpCodes.Call, setMethod);

					if (fieldBuilder != null)
					{
						Label dl = ilGenerator.DefineLabel();
						ilGenerator.Emit(OpCodes.Ldarg_0);
						ilGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
						ilGenerator.Emit(OpCodes.Ldnull);
						ilGenerator.Emit(OpCodes.Ceq);
						ilGenerator.Emit(OpCodes.Brtrue_S, dl);

						ilGenerator.Emit(OpCodes.Ldarg_0);
						ilGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
						ilGenerator.Emit(OpCodes.Ldarg_0);
						ilGenerator.Emit(OpCodes.Ldstr, pi.Name);
						ilGenerator.Emit(OpCodes.Newobj, typeof(PropertyChangedEventArgs).GetConstructor(new Type[] { typeof(string) }));
						ilGenerator.Emit(OpCodes.Callvirt, typeof(PropertyChangedEventHandler).GetMethod("Invoke"));
						ilGenerator.MarkLabel(dl);
					}

					ilGenerator.MarkLabel(el);
					ilGenerator.Return();
					pb.SetSetMethod(methodBuilder);
				}
			}

			// implement methods
			foreach (MethodInfo mi in typeof(T).GetAllVisibleMethods())
			{
				MethodBuilder methodBuilder = typeBuilder.DefineMethod(
					mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, mi.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ILGenerator ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.Emit(OpCodes.Ldarg_0);
				ilGenerator.Emit(OpCodes.Ldfld, inner);
				ilGenerator.LoadAllArguments(mi);
				ilGenerator.Emit(OpCodes.Callvirt, mi);
				ilGenerator.Return();
			}

			// implement events
			foreach (EventInfo ei in typeof(T).GetAllVisibleEvents())
			{
				// define event
				EventBuilder eb = typeBuilder.DefineEvent(ei.Name, EventAttributes.None, ei.EventHandlerType);
				MethodBuilder methodBuilder;
				ILGenerator ilGenerator;

				//
				// implement add method
				//
				MethodInfo addMethod = ei.GetAddMethod();
				methodBuilder = typeBuilder.DefineMethod(
					addMethod.Name, _methodAttributes, addMethod.ReturnType, addMethod.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.Emit(OpCodes.Ldarg_0);
				ilGenerator.Emit(OpCodes.Ldfld, inner);
				ilGenerator.Emit(OpCodes.Ldarg_1);
				ilGenerator.Emit(OpCodes.Callvirt, addMethod);
				ilGenerator.Return();
				eb.SetAddOnMethod(methodBuilder);

				//
				// implement remove method
				//
				MethodInfo removeMethod = ei.GetRemoveMethod();
				methodBuilder = typeBuilder.DefineMethod(
					removeMethod.Name, _methodAttributes, removeMethod.ReturnType, removeMethod.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.Emit(OpCodes.Ldarg_0);
				ilGenerator.Emit(OpCodes.Ldfld, inner);
				ilGenerator.Emit(OpCodes.Ldarg_1);
				ilGenerator.Emit(OpCodes.Callvirt, removeMethod);
				ilGenerator.Return();
				eb.SetRemoveOnMethod(methodBuilder);
			}

			return Activator.CreateInstance(typeBuilder.CreateType(), obj) as T;
		}

        private static readonly IDictionary<Type, Type> _notifyPropertyChangedTypeCache = new Dictionary<Type, Type>();
	}
}